from django.http import JsonResponse, HttpResponse

from django.contrib.auth import authenticate, login, logout
from django.template.context_processors import csrf
from django.contrib.auth.models import User
from django.views.decorators.http import require_http_methods
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from collections import defaultdict
from  common import models
from apiutils.response import ApiResponse
from rest_framework.decorators import permission_classes, api_view
from rest_framework.permissions import IsAuthenticated

from config.settings import LOGIN_URL
from mgr.common import get_framemenu


#shp2025_2_7 生成 csrf 数据，发送给前端
def get_csrf(request):
    x = csrf(request)
    csrf_token = x['csrf_token']
    return HttpResponse('{} ; {}'.format(str(request), csrf_token))


#shp2025_2_7 注册处理,注册成功后直接进行登录
@require_http_methods(["POST"])
def signup(request):
    if request.method == 'POST':
        userName = request.POST.get('username')
        passWord = request.POST.get('password')
        # 注册成功跳转到到登录页面，注册加判断已经存在提示改用用户已存在
        users = models.UserProfile.objects.all()
        for i in users:
            if userName == i.username:
                return JsonResponse({'code': -1, 'msg': '用户已存在'})
        try:
            models.UserProfile.objects.create_user(userName, "lennon@thebeatles.com" ,passWord)
            #shp_2025_2_7 直接登录
            # 使用 Django auth 库里面的 方法校验用户名、密码
            user = authenticate(username=userName, password=passWord)
            login(request, user)

            return ApiResponse(code=0, message="注册成功").to_json()
        except Exception as e:
            return ApiResponse(code=1, message="注册失败").to_json()
        #return JsonResponse({'username': userName, 'password': passWord})
    else:
        return ApiResponse(code=1, message="请求方式错误").to_json()
        #return render(request, '')


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_menu(request):
    """
    2025-04-15 shp新增判断用户权限，并动态给用户链接
    :param request:
    :return:
    """
    user = request.user
    permission_level = 1
    if user.is_staff:
        permission_level =2
    if user.is_superuser:
        permission_level =3
    menu_list = get_framemenu(permission_level)
    try:
        grouped_menus = defaultdict(list)

        for menu in menu_list:
           #处理路径为空的情况（根据 menu_id 生成默认路径）
            if not menu['path']:
                menu['path'] = f"/home/cd_{menu['menu_id'][-1]}"  # 示例规则：取 menu_id 最后一位

            child = {
                "menuid": menu['menu_id'],
                "title": menu['title'],
                "path": menu['path'],

            }
            #按父级名称分组
            grouped_menus[menu['fratitle']].append(child)
            result = []
            for parent_title, children in grouped_menus.items():
                parent_node = {
                    "parent_id": menu['id'],
                    "title": parent_title,
                    "children": children
                }
                result.append(parent_node)

        return ApiResponse.success(data=result)
    except Exception as e:

        return ApiResponse(code=1, message=f"服务器出现错误，错误原因：{e}").to_json()

#shp2025_2_7 登录处理
@require_http_methods(["POST"])
def signin(request):
    if request.method == 'POST':
        # 从 HTTP POST 请求中获取用户名、密码参数
        userName = request.POST.get('username')
        passWord = request.POST.get('password')

        # 使用 Django auth 库里面的 方法校验用户名、密码
        user = authenticate(username=userName, password=passWord)

        # 如果能找到用户，并且密码正确
        if user is not None:
            if user.is_active:
                #判断是否是管理员

                # if user.is_superuser:
                #     login(request, user)
                #     # 在session中存入用户类型
                #     request.session['usertype'] = 'mgr'
                #     return JsonResponse({'ret': 2, 'msg': '登录成功'})
                # else:
                #     login(request, user)
                #     # 在session中存入用户类型
                #     request.session['usertype'] = 'mgr'
                #     return JsonResponse({'ret': 1, 'msg': '请使用管理员账户登录'})
                #     login(request, user)
                login(request, user)
             #直接登录补判断是否为管理员
                request.session['usertype'] = 'mgr'
                return ApiResponse(code=0, message="登录成功").to_json()
            else:
                return ApiResponse(code=1, message="用户名已禁用").to_json()

        # 否则就是用户名、密码有误
        else:
            return ApiResponse(code=2, message="用户名或密码有误").to_json()
    else:
        return ApiResponse(code=1, message="请求方式错误").to_json()

#shp2025_2_7 登出处理
def signout(request):
    # 使用登出方法
    try:
        logout(request)
        return  ApiResponse(code=0, message="登出成功").to_json()
    except Exception as e:
        return ApiResponse(code=1, message="登出失败").to_json()

#获取个人信息
def getrmbuserone(request):
    repost = {
        "id" : request.user.id,
        "nick_name" : request.user.nick_name,
        "birthday": request.user.birthday,
        "gender": request.user.gender,
        "wechat": request.user.wechat,
        "mobile": request.user.mobile,
        "address": request.user.address,
        "positionid": request.user.positionid,
        "departmentid": request.user.departmentid,
    }
    return  JsonResponse(repost)

#判断首页是否登录
def root_redirect(request):
    # 未登录用户跳转到登录页
    if not request.user.is_authenticated:
        return redirect(LOGIN_URL)
    # 已登录用户跳转到主页（根据需求调整）
    return redirect('/mgr/view/frame')  # 替换为你的实际主页路径


